package com.heima.wemedia.service.iml;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl  extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${file.oss.prefix}")
    String prefix;
    @Value("${file.oss.web-site}")
    String webSite;

    /*
    * 上传图片，不仅在数据库中存储，还在oss中也存储一份
    * */
    @Override
    public ResponseResult<WmMaterial> uploadImages(MultipartFile multipartFile) {
       //1.校验参数,
        if (multipartFile == null || multipartFile.getSize()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"参数不存在或是文件为空");
        }
        //2.检验文件的格式是否为png,jpg,jpeg,gif
        String originalFilename = multipartFile.getOriginalFilename();
          if (!checkFileSuffix(originalFilename)){
              return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"素材格式不正确");
          }
        //3.检查用户是否登录
        WmUser wmUser = WmThreadLocalUtils.getWmUser();
          if (wmUser==null){
              return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"用户未登录");

          }
        //4.文件上传到oss，将oss中的图片路径，。
           String fileId = null;
          try {
              String filename = UUID.randomUUID().toString().replaceAll("-", "");
              //截取后缀名,lastIndexOf位置索引，substring截取从这个索引后的所有数据
              String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
              fileId = fileStorageService.store(prefix, filename + suffix, multipartFile.getInputStream());
              log.info("阿里云OSS 文件 fileId: {}",fileId);
          }catch (IOException e){
              e.printStackTrace();
              log.error("阿里云文件上传失败 uploadPicture error: {}"+e);
          }
         //保存到素材表中
        WmMaterial wmMaterial = new WmMaterial();
          //收藏類型，默認是不收藏
        wmMaterial.setIsCollection((short) 0);
        //素材類型，圖片，視頻
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUrl(fileId);
        wmMaterial.setUserId(wmUser.getId());
        save(wmMaterial);
        //前端顯示的路徑為website+fileid
        wmMaterial.setUrl(webSite+fileId);
        return ResponseResult.okResult(wmMaterial);
    }
/*
* 查询素材列表
* */
    @Override
    public ResponseResult<WmMaterial> findList(WmMaterialDTO wmMaterialDTO) {
       //1.参数校验，用户是否登录
          wmMaterialDTO.checkParam();
        WmUser wmUser = WmThreadLocalUtils.getWmUser();
        if (wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"用户未登录");
        }
        //2.查询,分页条件，是否收藏
        Page pageReq = new Page<>(wmMaterialDTO.getPage(), wmMaterialDTO.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery();
        if (wmMaterialDTO.getIsCollection() != null && wmMaterialDTO.getIsCollection().intValue()==1){
            wrapper.eq(WmMaterial::getIsCollection,wmMaterialDTO.getIsCollection());
        }
        //用户id
        wrapper.eq(WmMaterial::getUserId,wmUser.getId());
        //降序排序根据创建时间
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        //3.执行查询
        IPage<WmMaterial> page = page(pageReq, wrapper);
         //查询出来的图片路径所有的都需要修改
        List<WmMaterial> records = page.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            for (WmMaterial record : records) {
                record.setUrl(webSite+record.getUrl());
            }
        }
        //返回结果
        return new PageResponseResult(wmMaterialDTO.getPage(),wmMaterialDTO.getSize(),page.getTotal(),page.getRecords());
    }

    /*
    * 删除素材
    * */
    @Override
    public ResponseResult<WmMaterial> deleteImage(Integer id) {
        //1.参数校验
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"参数为空");
        }
        //2.进行业务处理删除素材，删除前判断素材是否被引用，被引用不能删除
          //先获取材料信息，判断是否被引用
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"该素材不存在");
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(WmNewsMaterial::getMaterialId,id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if (count >0){ //根据材料id在文章材料库中找到引用了，就不能删除
            return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW,"素材被引用了");
        }
        //3.删除数据库中的数据
        this.removeById(id);
        //删除oss云存储空间的素材数据
        fileStorageService.delete(wmMaterial.getUrl());
        //结果返回
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /*
    * 图片收藏与取消
    * */
    @Override
    public ResponseResult<WmMaterial> updateStatus(Integer id,short type) {
        //1.校验参数
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"参数不能为空");
        }
        //2.更新状态,只允许收藏自己上传的素材
           //2.1查询图片信息
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"图片不存在");
        }
        WmUser wmUser = WmThreadLocalUtils.getWmUser();
        if (!wmMaterial.getUserId().equals(wmUser.getId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW,"不是自己上传的图片不能收藏");
        }
          wmMaterial.setIsCollection(type);
           this.updateById(wmMaterial);
        return ResponseResult.okResult();
    }

    //判断上传文件格式是否正确
    private boolean checkFileSuffix(String originalFilename) {
        if (StringUtils.isBlank(originalFilename)){
            return false;
        }
        List<String> allowSuffix = Arrays.asList("jpg", "jpeg", "png", "gif");
        for (String suffix : allowSuffix) {
            if (originalFilename.endsWith(suffix)){
                return true;
            }
        }
        return false;
    }
}
